package com.dropgame.main;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Json;

public class MultipleProfileService {

	private static final String handleStart = "profile1";
	private static final String handleEnd = ".json";
	
	
	public Profile profile1;
	public Profile profile2;
	
	
	// Load all the profiles
	public void loadProfiles(){
		Json json = new Json();
		for(int i = 1; i <= 2; i++){
			FileHandle profileDataFile = Gdx.files.external(handleStart + Integer.toString(i) + handleEnd);
			
			if(profileDataFile.exists()){
				Gdx.app.log(DropGame.LOG, "Profile" + i + " exists");
				
				try{
					
					String profileAsCode = profileDataFile.readString();
					
					// check for Base 64 encoding here
					
					String profileAsText = profileAsCode;
					
					// restore the state
					
					if(i == 1) profile1 = json.fromJson(Profile.class, profileAsText);
					if(i == 2) profile2 = json.fromJson(Profile.class, profileAsText);
					
				} catch (Exception e){
					// Log the exception
					Gdx.app.error(DropGame.LOG, "Unable to parse existing profile data file " , e);
					
					// recover by creating a fresh new profile data file;
					// note that the player will lose all game progress
					
					//profile = new Profile();
					//persist(profile);
					}
			}
			
			
		}
	}
	
	// Return the profile that contains default = true
	// And sets the other profiles default to true so
	// There can only be one default profile
	public Profile returnDefault(){
		if(profile1.defaultProfile){ 
			profile2.defaultProfile = false;
			return profile1;}
		else if (profile2.defaultProfile){ 
			profile1.defaultProfile = false;
			return profile2;}
		else { profile2.defaultProfile = false;
			return profile1;
		}
	}
	
	// Save a given profile.
	public void persist(Profile profile){
		Gdx.app.log(DropGame.LOG, "Persisting profile In multiple profile");
		
		// Create the JSON utility object
		Json json = new Json();
		
		// Create handle for profile data file
		FileHandle profileDataFile = Gdx.files.external(handleStart + Integer.toString(profile.profileID) + handleEnd);
		
		// Convert the given profile to text
		String profileAsText = json.toJson(profile);
		
		// Base 64 encoding will go here
		
		String profileAsCode = profileAsText;
		
		Gdx.app.log(DropGame.LOG, "The text to be persisted is " + profileAsCode);
		
		// Write the profile data file
		profileDataFile.writeString(profileAsCode, false);
	}
	
	// Save all the profiles.
	public void persistAll(){
		persist(profile1);
		persist(profile2);
	}
	
	// Save the default profile.
	public void persistDefault(){
		if(profile1.defaultProfile) persist(profile1);
		else if(profile2.defaultProfile) persist(profile2);
	}
}
